package net.wsfcp.android.http.mvp.transformer;


import android.util.Log;

import net.wsfcp.android.base.BaseHttpResult;
import net.wsfcp.android.http.exception.ErrorType;
import net.wsfcp.android.http.exception.ServerException;


import org.reactivestreams.Publisher;

import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.functions.Function;


/**
 * Created by Shaoboyang on 2018/12/14.
 */

public class ErrorTransformer<T> implements FlowableTransformer<BaseHttpResult<T>, T> {

    private static ErrorTransformer errorTransformer = null;
    private static final String TAG = "ErrorTransformer";

    @Override
    public Publisher<T> apply(Flowable<BaseHttpResult<T>> upstream) {
        return upstream.map(new Function<BaseHttpResult<T>, T>() {
            @Override
            public T apply(BaseHttpResult<T> tBaseHttpResult) {
                if (tBaseHttpResult.getResultCode() == ErrorType.SUCCESS)
                    return tBaseHttpResult.getBody();
                throw new ServerException(tBaseHttpResult.getResultCode(), tBaseHttpResult.getResultMsg());
            }
        });
    }
//    .onErrorResumeNext(new Function<Throwable, Publisher<? extends T>>() {
//        @Override
//        public Publisher<? extends T> apply(Throwable throwable) {
////                return null;
//            throw new ServerException(0000, throwable.getMessage());
//        }
//    })


    /**
     * @return 线程安全, 双层校验
     */
    public static <T> ErrorTransformer<T> getInstance() {
        if (errorTransformer == null) {
            synchronized (ErrorTransformer.class) {
                if (errorTransformer == null) {
                    errorTransformer = new ErrorTransformer<>();
                }
            }
        }
        return errorTransformer;
    }


}
